package cn.wht.enginee;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

/**
 * txt 文本解析
 * 
 * @Author: haoting.wang
 * @Date: Created in 上午10:56 2017/6/16
 */
public class TextParseEnginee extends ParseEnginee {

    public TextParseEnginee(BlockingQueue<Map> queue, File file){
        this.queue = queue;
        this.file = file;
    }

    @Override
    public void parseFileToQueue(BlockingQueue<Map> queue, File file) {
        FileInputStream is = null;
        String line = "";
        Map dataRow = new HashMap();
        int i = 0;
        try {
            if (file.exists()) {
                is = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = br.readLine()) != null) {
                    if (line.trim().length() > 0) {
                        String[] data = line.split(",");
                        for (int index = 0; index < data.length; index++) {
                            dataRow.put(String.valueOf(index), data[index]);
                        }
                        queue.put(dataRow);
                        dataRow = new HashMap();
                        i++;
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("import was interrupted, error happened in " + i + "  row", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                    is = null;
                }
            } catch (Exception e) {
                is = null;
                logger.error("FileInputStream close error message={}", e.getMessage());
            }
        }
    }

}
